package com.gzx.spring.apis.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzx.risk.core.apis.context.ApiContext;
import com.gzx.risk.core.apis.result.RiskResult;
import com.gzx.risk.core.apis.result.jishu.JishuEd006_v1;
import com.gzx.risk.core.apis.result.jishu.JishuEdb003_v8;
import com.gzx.spring.apis.utils.JishuUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class JishuService {
	@Value("${apis.jishu.appId}")
	private String appId;
	@Value("${apis.jishu.appSecret}")
	private String appSecret;
	@Value("${apis.jishu.apiUrl}")
	private String apiUrl;

	@Value("${apis.jishu.env}")
	private String env;

	private final ObjectMapper objectMapper;

	public JishuService(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	public String ed006_v1(String id, String phone) throws Exception {
        if ("debug".equals(env)) {
            return ApiExec.loadJson("/debug/jishu/ed006_v1");
        }
		JishuUtil util = new JishuUtil().apiUrl(apiUrl).appId(appId).appSecret(appSecret);
		return util.ed006_v1(id, phone);
	}

	public String edb003_v8(String name, String id, String phone) throws Exception {
        if ("debug".equals(env)) {
            return ApiExec.loadJson("/debug/jishu/edb003_v8");
        }
        JishuUtil util = new JishuUtil().apiUrl(apiUrl).appId(appId).appSecret(appSecret);
		return util.edb003_v8(name, id, phone);
	}

	public RiskResult ed006_v1(String groupName, ApiContext ctx) throws Exception {
		String apiName = "jishu_ed006_v1";
		String json = this.ed006_v1(ctx.getUserInfo().getId(), ctx.getUserInfo().getPhone());
        log.debug("{}:{}", apiName, json);

		JishuEd006_v1 obj = objectMapper.readValue(json, JishuEd006_v1.class);
		obj.setGroupName(groupName);
		obj.setDataName(apiName);
		if ("200".equals(obj.getCode())) {
			ctx.add(obj);
		} else {
			log.warn("{},code:{},msg:{}", apiName, obj.getCode(), obj.getMsg());
		}
		return obj;
	}

	public RiskResult edb003_v8(String groupName, ApiContext ctx) throws Exception {
		String apiName = "jishu_edb003_v8";
		String json = this.edb003_v8(ctx.getUserInfo().getName(), ctx.getUserInfo().getId(), ctx.getUserInfo().getPhone());
        log.debug("{}:{}", apiName, json);

		JishuEdb003_v8 obj = objectMapper.readValue(json, JishuEdb003_v8.class);
		obj.setGroupName(groupName);
		obj.setDataName(apiName);
		if ("200".equals(obj.getCode())) {
			ctx.add(obj);
		} else {
			log.warn("{},code:{},msg:{}", apiName, obj.getCode(), obj.getMsg());
		}
		return obj;
	}
}
